import Vue from 'vue'
import VueRouter from 'vue-router'
import { Dialog } from 'vant'
import store from '@/store'

Vue.use(VueRouter)

const routes = [
  {
    name: 'login',
    path: '/login',
    component: () => import('@/views/login')
  },
  {
    name: 'layout',
    path: '/',
    component: () => import('@/views/layout'),
    children: [
      {
        name: 'home',
        path: 'home',
        component: () => import('@/views/home')
      },
      {
        name: 'qa',
        path: 'qa',
        component: () => import('@/views/qa')
      },
      {
        name: 'video',
        path: 'video',
        component: () => import('@/views/video')
      },
      {
        name: 'my',
        path: 'my',
        component: () => import('@/views/my'),
      },
    ]
  },
  {
    name: 'search',
    path: '/search',
    component: () => import('@/views/search')
  },
  {
    path: '/article/:articleId',
    name: 'article',
    component: () => import('@/views/article'),
    props: true
  },
  {
    path: '/user/profile',
    name: 'user-profile',
    component: () => import('@/views/user-profile'),
    meta: { requiresAuth: true }
  },
  {
    path: '/user/chat',
    name: 'user-chat',
    component: () => import('@/views/user-chat'),
    meta: { requiresAuth: true }
  },
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  const user = store.state.user
  if (to.meta.requiresAuth) {
    // 校验登录状态
    if (user) return next()

    Dialog.confirm({
      title: '访问提示',
      message: '需要登录才能访问，确认登录吗？'
    }).then(() => { //  点击确认执行该函数
      next({
        name: 'login',
        query: {
          redirect: from.fullPath
        }
      })
    }).catch(() => {  // 点击取消执行该函数
      next(false)
    })
  } else if (to.path === '/login') {
    user ? next('/my') : next()
  } else {
    next()
  }

})

export default router
